<template>
  <div id="mainBar" style="width: 100%; height: 100%"></div>
</template>
<script setup name="EcharstBar">
import * as echarts from 'echarts'
import { reactive, toRefs, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()

const props = defineProps({
  barObj: {
    type: Object,
    require: true
  }
})
let mainBar = null
const data = reactive({
  // 圆饼图配置信息
  option: {},
  // echarts绑定dom
  // mainBar: null,
  // echarts所需数据
  echartsData: [],
  // 标题
  title: '',
  xLabel: ['1月', '2月', '3月', '4月', '5月', '6月'],
  color: [
    '#fd8d9d',
    '#86adfb',
    '#ee6666',
    '#b2c095',
    '#73c0de',
    '#3ba272',
    '#fc8452',
    '#9a60b4',
    '#ea7ccc',
    '#5470c6',
    '#5c22e4',
    '#cadb2c',
    '#2cb2db',
    '#5c38df',
    '#df9138',
    '#ff00ff',
    '#38dfdf',
    '#2270e4',
    '#30c92b',
    '#9438df',
    '#4082b9',
    '#40b950',
    '#eeeb59',
    '#ee9c59',
    '#f53a21',
    '#27eb27',
    '#217df5',
    '#f5214f',
    '#5a40b9',
    '#27ebeb',
    '#b221f5',
    '#38df62',
    '#b2df38',
    '#c7162e',
    '#24c716'
  ]
})
let { option, echartsData, title, xLabel, color } = toRefs(data)
watch(
  () => props.barObj,
  () => {
    title.value = props.barObj?.title
    echartsData.value = props.barObj?.dataOption
    xLabel.value = props.barObj?.xLabel
    proxy.$nextTick(() => {
      echartsDraw()
    })
  },
  {
    deep: true,
    immediate: true
  }
)

function echartsDraw() {
  if (mainBar != null && mainBar != '' && mainBar != undefined) {
    mainBar.dispose() // 销毁
  }
  mainBar = echarts.init(document.getElementById('mainBar'))
  option.value = {}
  option.value = {
    color: color.value,
    title: {
      text: title.value
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      top: 'bottom'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      axisTick: {
        alignWithLabel: true
      },
      data: xLabel.value
    },
    yAxis: {
      type: 'value'
    },
    series: computed(() => {
      return echartsData.value.map(item => {
        return {
          name: item.name,
          type: 'bar',
          data: item.data
        }
      })
    })
    // series: [
    //   {
    //     name: echartsData.value[0].name,
    //     type: 'bar',
    //     data: echartsData.value[0].data
    //   },
    //   {
    //     name: echartsData.value[1].name,
    //     type: 'bar',
    //     data: echartsData.value[1].data
    //   }
    // ]
  }
  mainBar.setOption({ ...option.value, ...props.barObj?.option })
}
</script>
<style lang="scss" scoped></style>
